<?php
/**
 * This is the administration_controller class file.
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class AdministrationController extends AppController
{
    # Controller Name to be used
    var $name = 'Administration';

    # Models to be used
    var $uses = array(
        'User',
        'Group',
        'Organisation',
        'Module',
        'Configuration'
    );

    # set the layout to use
    var $layout = 'administration_layout';

    # set the name of this module
    var $moduleName = 'Administration';

    # Check the authenticity of the user
    function  beforeFilter()
    {
        parent::beforeFilter($this->moduleName);
        parent::setUpGlobalConfig();
    }

    # Controller actions
    /**
     * This function displays all the users in the system
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index(){

        $group_data = Set::combine($this->Group->find('all',array(
            'fields'=>array('id','name'),
            'conditions' => array('deleted'=>'n','active'=>'y'),
            'recursive'=>-1)),
        '{n}.Group.id', '{n}.Group');
        $groupOpt = array();
        foreach($group_data as $value){
            $groupOpt[$value['id']] = $value['name'];
        }

        # List of all the modules in the system
        $allModules = $this->Module->find('all', array(
            'conditions'=>array('Module.active'=>1),
            'recursive' => -1,
            'order' => 'Module.name ASC'
        ));


        $page_title = 'Administration';
        $this->set(compact('page_title','groupOpt','allModules'));
    }

    function groups(){
        # List of all the modules in the system
        $allModules = $this->Module->find('all', array(
            'conditions'=>array('Module.active'=>1),
            'recursive' => -1,
            'order' => 'Module.name ASC'
        ));

        $page_title = 'Administration';
        $this->set(compact('page_title','allModules'));
    }

    function companys_profile(){
        $Org = $this->Organisation->find('first', array('recursive' => -1));

        if(isset($Org['Organisation']['date_of_establishment'])){
            $Org['Organisation']['date_of_establishment'] = $this->covertDate($Org['Organisation']['date_of_establishment'],'ui');
        }
        $page_title = 'Administration';
        $this->set(compact('page_title','Org'));
    }

    function settings(){
        $allConfiguration =  Set::combine($this->Configuration->find('all', array(
            'recursive' => -1,
            'order' => 'Configuration.key ASC')),
        '{n}.Configuration.id', '{n}.Configuration');

        $page_title = 'Administration';
        $this->set(compact('page_title','allConfiguration'));
    }

    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function add(){
        # Get the user session data
        $loggedUser = $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch ($model) {
                case 'User' :
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $loggedUser_id = $loggedUser['id'];

                    if ($upt_id) {
                        /** Edit User*/
                        $this->User->id = $upt_id;
                        //$userObj = new User($upt_id);
                        /** Delete All users modules and insert new ones*/
                        //$this->User->ModulesUser->deleteAll(array('ModulesUser.user_id' => $upt_id), false);
                    }
                    else {
                        /** New User*/
                        $this->User->create();
                        // $userObj = new User();
                    }

                    //$this->User->bindModel(array('hasMany'=>array('ModulesUser')));

                    # save the data
                    if ($this->User->save($this->request->data)) {
                        return json_encode(array('code' => 0, 'mesg' => __('Data Saved')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => $this->User->invalidFields()));
                    }
                    /**
                    if($upt_id){
                    if($this->User->save($this->request->data['User'])){
                    //  debug($this->data['ModulesUser']);
                    $mod_arr = array();
                    foreach($this->data['ModulesUser'] as $row){
                    $mod_arr[] = array(
                    'module_id' => $row['module_id'],
                    'user_id' => $upt_id
                    );
                    }
                    $this->request->data['ModulesUser'] = $mod_arr;
                    //debug($this->data['ModulesUser']);
                    // return json_encode(array('code' => 0, 'mesg' => __('User Data successfully recorded',true)));
                    $res = $this->User->ModulesUser->saveAll($this->request->data['ModulesUser']);
                    if($res){
                    return json_encode(array('code' => 0, 'mesg' => __('Data Saved')));
                    }
                    else{
                    return json_encode(array('code' => 1, 'mesg' => $res));
                    }
                    }
                    else{
                    return json_encode(array('code' => 1, 'mesg' => $userObj->invalidFields()));
                    }
                    }
                    else{
                    if($this->User->saveAll($this->request->data)){
                    return json_encode(array('code' => 0, 'mesg' => __('Data Saved')));
                    }
                    else{
                    return json_encode(array('code' => 1, 'mesg' => $this->User->invalidFields()));
                    }
                    }*/

                    break;

                case 'Group' :
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $loggedUser_id = $loggedUser['id'];

                    if ($upt_id) {
                        /** Edit User*/
                        $this->Group->id = $upt_id;
                        //$userObj = new User($upt_id);
                        /** Delete All users modules and insert new ones*/
                        $this->Group->ModulesGroup->deleteAll(array('ModulesGroup.group_id' => $upt_id), false);
                    }
                    else {
                        /** New User*/
                        $this->Group->create();
                        // $userObj = new User();
                    }

                    $this->Group->bindModel(array('hasMany' => array('ModulesGroup')));

                    # save the data
                    if ($upt_id) {
                        if ($this->Group->save($this->request->data['Group'])) {
                            //  debug($this->data['ModulesUser']);
                            $mod_arr = array();
                            foreach ($this->data['ModulesGroup'] as $row) {
                                $mod_arr[] = array(
                                    'module_id' => $row['module_id'],
                                    'group_id' => $upt_id
                                );
                            }
                            $this->request->data['ModulesGroup'] = $mod_arr;
                            //debug($this->data['ModulesUser']);
                            // return json_encode(array('code' => 0, 'mesg' => __('User Data successfully recorded',true)));
                            $res = $this->Group->ModulesGroup->saveAll($this->request->data['ModulesGroup']);
                            if ($res) {
                                return json_encode(array('code' => 0, 'id' => $upt_id, 'mesg' => __('Data Saved')));
                            }
                            else {
                                return json_encode(array('code' => 1, 'mesg' => $res));
                            }
                        }
                        else {
                            return json_encode(array('code' => 1, 'mesg' => $this->Group->invalidFields()));
                        }
                    }
                    else {
                        if ($this->Group->saveAll($this->request->data)) {
                            return json_encode(array('code' => 0, 'id' => $this->Group->id, 'mesg' => __('Data Saved')));
                        }
                        else {
                            return json_encode(array('code' => 1, 'mesg' => $this->Group->invalidFields()));
                        }
                    }

                    break;

                case 'Organisation':

                    if(isset($this->request->data['Organisation']['date_of_establishment'])){
                        $this->request->data['Organisation']['date_of_establishment'] = $this->covertDate($this->request->data['Organisation']['date_of_establishment'],'mysql');
                    }
                    /* Update the data  */
                    if (!empty($this->request->data)) {

                        if ($this->Organisation->save($this->request->data)) {
                            return json_encode(array('code' => 0, 'data' => $this->request->data['Organisation'], 'mesg' => __('Data successfully saved. You need to reload the page for the new changes to be applied')));
                        }
                        else {
                            return json_encode(array('code' => 1, 'data' => $this->request->data['Organisation'], 'mesg' => __('Data not saved')));
                        }
                    }

                    break;

                case 'Modules':

                    /* Update the data */
                    if (!empty($this->data)) {

                        if ($this->Module->saveAll($this->data['Module'])) {
                            return json_encode(array('code' => 0, 'mesg' => __('Modules Configuration Saved!')));
                        }
                        else {
                            return json_encode(array('code' => 1, 'mesg' => __('Modules Configuration not Saved')));
                        }
                    }

                    break;

                case 'SystemConfig':
                    /* Update the data */
                    if (!empty($this->data)) {

                        if ($this->Configuration->saveAll($this->data['Configuration'])) {
                            return json_encode(array('code' => 0, 'mesg' => __('System Configuration Saved!')));
                        }
                        else {
                            return json_encode(array('code' => 1, 'mesg' => __('System Configuration not Saved')));
                        }
                    }
                    break;

            }
        }
    }


    /**
     * This function load the add user form
     * @param void
     * @return html
     * @access public
     */
    function loadUser()
    {
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        $userData = $this->User->getUserById($_POST['user-id']);

        if ($userData) {
            return json_encode(array('code' => 0, 'data' => $userData, 'mesg' => __('Data Found')));
        }
        else {
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    #Delete Users via ajax
    function deleteUsers()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            $ids = $_POST['ids'];
            $user = ClassRegistry::init('User');
            $result = $user->updateAll(
                array('User.deleted' => "'y'"),
                array('User.id' => $ids)
            );

            if ($result) {
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Users have been successfully deleted')));
            }
            else {
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Users cannot be deleted')));
            }
        }
    }


    /**
     * @name getUsers
     * @param void
     * @return Json Data
     */
    function getUsers()
    {
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;

        $condition_array = array('User.deleted' => 'n');
        if (!empty($search_query)) {
            if ($search_query == 'username') {
                $condition_array = array(
                    'User.username' => $search_query,
                    'User.deleted' => 'n'
                );
            }
            else {
                $condition_array = array(
                    "User.$qtype LIKE" => $search_query . '%',
                    'User.deleted' => 'n'
                );
            }
        }

        $fields = array('User.id', 'User.username', 'User.first_name', 'User.last_name', 'User.group_id', 'User.active');
        $users = $this->User->find('all', array('fields' => $fields, 'conditions' => $condition_array, 'order' => "User.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
        $usersCount = $this->User->find('count', array('conditions' => $condition_array, 'recursive' => -1));

        $total_records = $usersCount;

        if ($users) {
            $return_arr = array();
            foreach ($users as $obj) {

                $status = $obj['User']['active'] == 'y' ? 'Active' : 'Inactive';
                $group = $this->Group->getGroupNameById($obj['User']['group_id']);

                $return_arr[] = array(
                    'id' => $obj['User']['id'],
                    'cell' => array(
                        $obj['User']['id'],
                        $obj['User']['username'],
                        $obj['User']['first_name'],
                        $obj['User']['last_name'],
                        $group,
                        $status
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }


    /**  Group Manage ********************************************************/

    function loadGroup()
    {
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        $objData = $this->Group->getGroupById($_POST['group-id']);

        $model_arr = array();
        if ($objData['Module']) {
            foreach ($objData['Module'] as $row) {
                $model_arr[] = $row['id'];
            }

            $objData['Module'] = $model_arr;
        }

        if ($objData) {
            return json_encode(array('code' => 0, 'data' => $objData, 'mesg' => __('Data Found')));
        }
        else {
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    #Delete Users via ajax
    function deleteGroups()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            $ids = $_POST['ids'];
            $obj = ClassRegistry::init('Group');
            $result = $obj->updateAll(
                array('Group.deleted' => "'y'"),
                array('Group.id' => $ids)
            );

            if ($result) {
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Groups have been successfully deleted')));
            }
            else {
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Groups cannot be deleted')));
            }
        }
    }


    /**
     * @name getUsers
     * @param void
     * @return Json Data
     */
    function getGroups()
    {
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;

        $condition_array = array('Group.deleted' => 'n');
        if (!empty($search_query)) {
            if ($search_query == 'name') {
                $condition_array = array(
                    'Group.name' => $search_query,
                    'Group.deleted' => 'n'
                );
            }
            else {
                $condition_array = array(
                    "Group.$qtype LIKE" => $search_query . '%',
                    'Group.deleted' => 'n'
                );
            }
        }

        $fields = array('Group.id', 'Group.name', 'Group.active');
        $objs = $this->Group->find('all', array('fields' => $fields, 'conditions' => $condition_array, 'order' => "Group.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
        $objsCount = $this->Group->find('count', array('conditions' => $condition_array, 'recursive' => -1));

        $total_records = $objsCount;

        if ($objs) {
            $return_arr = array();
            foreach ($objs as $obj) {

                $status = $obj['Group']['active'] == 'y' ? 'Active' : 'Inactive';

                $return_arr[] = array(
                    'id' => $obj['Group']['id'],
                    'cell' => array(
                        $obj['Group']['id'],
                        $obj['Group']['name'],
                        $status
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }


    /**
     * This function upload file
     * @name uploadFile
     * @param void
     * @return html data
     * @access public
     */
    function uploadFile()
    {
        $this->autoRender = false;
        $this->autoLayout = false;

        # Get the user session data
        $loggedUser = $this->Auth->user();

        $this->Organisation->id = $_POST['org-id'];
        # folder path structure
        $folder = 'img/uploaded_files/';
        $folder_db = 'uploaded_files/';

        # setup directory pathname
        $folderAbsPath = WWW_ROOT . $folder;
        $folderRelPath = $folder;

        # create folders if it does not exist
        if (!is_dir($folderAbsPath)) {
            mkdir($folderAbsPath, 0777, true);
        }

        # get the file details
        $rawFile = $folderAbsPath . basename($_FILES['uploadfile']['name']);
        $rawFile_rel = $folder_db . basename($_FILES['uploadfile']['name']);

        // replace spaces with underscores
        $fileName = str_replace(' ', '_', $rawFile);
        $fileName_rel = str_replace(' ', '_', $rawFile_rel);

        $fileType = $_FILES['uploadfile']['type'];

        # list of permitted file types, this is only images but documents can be added
        $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');

        $typeOk = false; # with the correct type the file will be uploaded or rejected.

        foreach ($permitted as $type) {
            if ($type == $fileType) {
                $typeOk = true;
                break;
            }
        }
        # if typeOk upload the file
        if ($typeOk) {
            # check whether the file already exists or not
            if (!file_exists($fileName)) {
                # upload the file
                if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $fileName)) {
                    # update the file details in the database
                    $this->data['Organisation'] = array(
                        'logo_path' => $fileName_rel,
                        'modified_by' => $loggedUser['id'],
                        'modification_date' => date('Y-m-d H:i:s')
                    );

                    if ($this->Organisation->save($this->data, false) == true) {
                        echo 0;
                    }
                    else if ($this->Organisation->save($this->data, false) == false) {
                        echo 1;
                    }
                }
                else {
                    echo 1;
                }
            }
            else {
                echo 2;
            }
        }
        else {
            echo 3;
        }
    }

}

?>
